package softswitch.service;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import softswitch.model.Circuit;
import softswitch.model.Offer;
import softswitch.model.Package;


@Stateless
public class PackageDAO {

	
	@PersistenceContext(unitName = "persistence")
    private EntityManager em;
	
	
	public Package getById(Integer id){	
		return em.find(Package.class, id);
	}
    
    public Package save(Package packag) {
    	em.persist(packag); 
    	return packag;
    }
    
    public Package update(Package packag) {
    	return em.merge(packag); 
    }
    
    public void delete(Integer id) {
    	em.remove(em.find(Package.class, id));	
    }
    
	@SuppressWarnings("unchecked")
    public List<Package> list(int first, int max) {    	
    	Query query = em.createQuery("SELECT e FROM Package e");
    	if (max > 0) {
            query.setMaxResults(max);
        }
    	if (first > 0) {
            query.setFirstResult(first);
        }
        return query.getResultList();   
    }
    
    //----------------------------------------------------------------------
    
	public Long countByCircuit(Circuit circuit) {
		String sql = " SELECT COUNT(*) FROM Package e WHERE  e.circuit=:circuit";
	
		Query query = em.createQuery(sql);
		query.setParameter("circuit", circuit);
		try{
			return (Long)query.getSingleResult();	
		}
		catch(Exception e){
			return null;
		}
	}
	
	
	@SuppressWarnings("unchecked")
	public List<Package> listByCircuit(Circuit circuit) {
    	List<Package> results = null;
    	Query query = em.createQuery("SELECT e FROM Package e WHERE e.circuit=:circuit");
    	query.setParameter("circuit", circuit);
    	try{
    		results = query.getResultList();
    	}
    	catch(NoResultException e){
    	}
        return results; 
    }
    
    @SuppressWarnings("unchecked")
	public List<Package> listByOffer(Offer offer) {
		Query query = em.createQuery("SELECT e FROM Package e WHERE e.offer=:offer");
    	query.setParameter("offer", offer);
        return query.getResultList(); 
	}
    
    @SuppressWarnings("unchecked")
	public List<Package> listByCircuitOffer(Circuit circuit, Offer offer) {	
       	Query query = em.createQuery("SELECT e FROM Package e WHERE e.circuit=:circuit AND e.offer=:offer");
       	query.setParameter("circuit", circuit);
       	query.setParameter("offer", offer);
        return query.getResultList(); 
    }
    
    
}

